package com.example.night.service.ApiService.yuantuitui;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import org.brotli.dec.BrotliInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import java.util.*;
import java.util.concurrent.CompletableFuture;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
public class LoginService {

    private static final String SEND_CODE_URL = "https://b.yuantuitui.com/api/login/sms/send";
    private static final String LOGIN_URL = "https://b.yuantuitui.com/api/login/sms/dynamic";
    private Map<String, String> phoneCodeMap = new HashMap<>();  // 保存手机号和验证码的映射

    boolean flag = false;

    private static String token = "";
    @Autowired
    private RestTemplate restTemplate;

    // 预设手机号列表
    private List<String> mobileNumbers = Arrays.asList(
            "18101409695",
            "15651616098"
    );

    // 发送验证码方法
    public String sendVerificationCode(String mobile) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json, text/plain, */*");
        headers.add("Accept-Encoding", "gzip, deflate, br");
        headers.add("Content-Type", "application/json;charset=utf-8");
        headers.add("Origin", "https://m.yuantuitui.com");
        headers.add("Referer", "https://m.yuantuitui.com/");
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");

        // 请求体
        String payload = "{\"mobile\": \"" + mobile + "\"}";
        HttpEntity<String> entity = new HttpEntity<>(payload, headers);

        try {
            // 发送请求并获取返回结果
            ResponseEntity<String> response = restTemplate.postForEntity(SEND_CODE_URL, entity, String.class);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "发送验证码失败：" + e.getMessage();
        }
    }

    public String loginWithSmsCode(String mobile, String code) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json, text/plain, */*");
        headers.add("Accept-Encoding", "gzip, deflate, br");
        headers.add("Content-Type", "application/json;charset=utf-8");
        headers.add("Origin", "https://m.yuantuitui.com");
        headers.add("Referer", "https://m.yuantuitui.com/");
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");

        // 登录请求的载荷
        String payload = "{\"mobile\": \"" + mobile + "\", \"code\": \"" + code + "\"}";
        HttpEntity<String> entity = new HttpEntity<>(payload, headers);

        try {
            ResponseEntity<byte[]> response = restTemplate.exchange(LOGIN_URL, HttpMethod.POST, entity, byte[].class);

            // 响应体转换
            String responseBody;
            if ("br".equals(response.getHeaders().getFirst("Content-Encoding"))) {
                responseBody = decompressBrotli(response.getBody());
            } else {
                responseBody = new String(response.getBody(), StandardCharsets.UTF_8);
            }

            System.out.println("登录响应: " + responseBody);

            // 使用 Jackson 解析响应
            ObjectMapper objectMapper = new ObjectMapper();
            LoginResponseYTT loginResponse = objectMapper.readValue(responseBody, LoginResponseYTT.class);

            // 提取 token
            if (loginResponse != null
                    && loginResponse.getData() != null
                    && loginResponse.getData().getResult() != null
                    && loginResponse.getData().getResult().getToken() != null) {
                String token = loginResponse.getData().getResult().getToken().getAccessToken();
//                System.out.println("登录成功，Token: " + token);
                this.token = token;
                return token;
            } else {
                System.out.println("登录失败，响应格式异常: " + responseBody);
                return "登录失败，响应格式异常";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "登录失败：" + e.getMessage();
        }
    }


    // 解压 Brotli 数据
    public String decompressBrotli(byte[] compressedData) throws IOException {
        try (InputStream brotliStream = new BrotliInputStream(new ByteArrayInputStream(compressedData))) {
            byte[] buffer = new byte[1024];
            StringBuilder output = new StringBuilder();
            int bytesRead;
            while ((bytesRead = brotliStream.read(buffer)) != -1) {
                output.append(new String(buffer, 0, bytesRead));
            }
            return output.toString();
        }
    }

    // 通过手机号和验证码的映射更新验证码
    public void setCode(String mobile, String receivedCode) {
        // 如果已经有验证码，避免再次写入
        if (!phoneCodeMap.containsKey(mobile)) {
            this.phoneCodeMap.put(mobile, receivedCode);  // 将手机号和验证码存入map

            if (flag == true) {
                String code = phoneCodeMap.get(mobile);
                String loginResult = loginWithSmsCode(mobile, code);
//                System.out.println("登录结果 - " + mobile + ": " + loginResult);
                flag = false;
                // 清空map，避免后续的处理
                phoneCodeMap.clear();
            }
        }
    }

    // 执行预设手机号的验证码发送和登录
    public void sendCodeAndLogin() {
        // 异步发送验证码
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        flag = true;
        for (String mobile : mobileNumbers) {
            futures.add(CompletableFuture.runAsync(() -> {
                String sendCodeResult = sendVerificationCode(mobile);
                System.out.println("验证码发送结果 - " + mobile + ": " + sendCodeResult);
            }));
        }

    }

    public String getToken() {
        return token;
    }
}
